import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { User } from './entities/user.entity';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
  ) {}

  async create(createUserDto: CreateUserDto) {
    const { username } = createUserDto;

    const existUser = await this.userRepository.findOne({ where: { username } });

    if (existUser) {
      throw new BadRequestException('用户名已存在');
    }

    const newUser = this.userRepository.create(createUserDto);
    newUser.nickname = '用户' + Math.floor(Math.random() * 10000);
    newUser.avatar = `https://i.pravatar.cc/150?u=${Math.random() * 10000}`;
    newUser.role = 'visitor';
    newUser.email = '';

    return this.userRepository.save(newUser);
  }

  async findAll(current: number = 1, pageSize: number = 10) {
    const [data, total] = await this.userRepository.findAndCount({
      skip: (current - 1) * pageSize,
      take: pageSize,
      order: { updateTime: 'DESC' }, // 可选，按id倒序
    });

    return {
      data,
      total,
      current,
      pageSize,
      pages: Math.ceil(total / pageSize),
    };
  }

  async findOne(id: string) {
    const user = await this.userRepository.findOne({ where: { id } });

    if (!user) {
      throw new BadRequestException('用户不存在');
    }

    return user;
  }

  async update(id: string, updateUserDto: UpdateUserDto) {
    const result = await this.userRepository.update(id, updateUserDto);

    if (result.affected === 0) {
      throw new NotFoundException(`User with id ${id} not found`);
    }

    return await this.userRepository.findOne({ where: { id } });
  }

  async remove(id: number) {
    const result = await this.userRepository.softDelete(id);
    if (result.affected === 0) {
      throw new Error(`User with id ${id} not found`);
    }
    return result;
  }
}
